package com.mimo.comet.dao.impl;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.mimo.comet.dao.ISessionDao;
import com.mimo.comet.provider.ISession;

@Repository
public class SessionDaoImpl implements ISessionDao {

  private static final int DEFAULT_INIT = 1024;

  private static final Map<String, ISession> locals = new ConcurrentHashMap<>(DEFAULT_INIT);

  @Override
  public Optional<ISession> findByUid(String uid) {
    return Optional.ofNullable(locals.get(uid));
  }

  @Override
  public long getSize() {
    return locals.size();
  }

  @Override
  public void create(ISession session) {
    Assert.isTrue(!locals.containsKey(session.getSessionId()), "同一账号,会话创建重复");
    locals.put(session.getSessionId(), session);
  }

  @Override
  public Optional<ISession> remove(String uid) {
    return Optional.ofNullable(locals.remove(uid));
  }

  @Override
  public Collection<ISession> listAll() {
    return locals.values();
  }

}
